﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.LALR;

namespace Contoso.VisualStudio.Generators
{
    [ComVisible(true)]
    [Guid("52A7B6C6-E3DA-4bfa-A27C-8F1CEFA3DDA1")]
    public class LALRReprint : VsSingleFileGeneratorWithSite
    {
        private Context _ctx;

        protected override void PreGenerateContent(string inputFilePath, string inputFileContents)
        {
            _ctx = new Context(Error, Warning);
            Parser.Parse(_ctx, inputFilePath, inputFileContents, null);
            if (_ctx.Errors > 0)
                return;
            if (_ctx.Rules == 0)
            {
                Warning(0, "Empty grammar.");
                return;
            }
        }

        protected override byte[] GenerateContent(string inputFilePath, string inputFileContents)
        {
            using (var s = new MemoryStream())
            {
                using (var w = new StreamWriter(s))
                    _ctx.Reprint(w);
                return s.ToArray();
            }
        }

        public override string GetDefaultExtension() { return ".out"; }
    }
}
